<?php

namespace App\Admin\Controllers;

use Slowlyo\OwlAdmin\Controllers\AdminController;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;
use App\Support\Components;

class ToolsController extends AdminController
{

    // 获取当月的所有天数
    public function getDaysOfMonth()
    {   
        // 获取请求参数month 为月份第一天的时间戳
        $month = request()->input('month');
        // 返回一个数组 该月份的第一天日期到该月份的最后一天日期
        $startDate = Carbon::createFromTimestamp($month)->startOfMonth();
        $endDate = Carbon::createFromTimestamp($month)->endOfMonth();
        
        $days = [];
        $currentDate = $startDate->copy();
        
        while ($currentDate <= $endDate) {
            $days[] = [
                'date' => $currentDate->format('Y-m-d')
            ];
            $currentDate->addDay();
        }
        
        return $this->response()->success([
            'days' => $days
        ]);
    }

    // 流量数据修正 
    public function flowDataCorrection()
    {
        return amis()->Page()->body([
            amis()->Form()->api('post:/tools/flow-data-correction')
            ->title('流量数据修正')
            ->body([
                amis()->Card()
                ->className('border-0')
                ->body([
                    // 顶部说明文字
                    amis()->Alert()
                        ->level('info')
                        ->showIcon(true)
                        ->body('对导出的流量数据进行以1.024的修正，上传csv文件来对文件内的流量数值进行统一的乘1.024操作'),

                    // 文件上传区域
                    amis()->FileControl('file')
                        ->label('')
                        ->accept('.xlsx')
                        ->drag(true)
                        ->multiple(false)
                        ->required(true)
                        ->joinValues(false),

                    // 操作按钮组
                    amis()->ButtonGroupControl()
                        ->name('operation')
                        ->className('mt-4')
                        ->label('')
                        ->value('multiply_1')
                        ->btnLevel('default')
                        ->btnActiveLevel('primary')
                        ->size('md')
                        ->id('operation')
                        ->options([
                            ['label' => '乘1次1.024', 'value' => 'multiply_1'],
                            ['label' => '乘2次1.024', 'value' => 'multiply_2'],
                            ['label' => '乘3次1.024', 'value' => 'multiply_3'],
                            ['label' => '除3次1.024', 'value' => 'divide_3'],
                            ['label' => '除2次1.024', 'value' => 'divide_2'],
                            ['label' => '除1次1.024', 'value' => 'divide_1'],
                            ['label' => '随机乘', 'value' => 'random_multiply'],
                            ['label' => '随机除', 'value' => 'random_divide']
                        ])
                        ->onEvent([
                            'change' => [
                                'actions' => [
                                    [
                                        'actionType' => 'submit',
                                        'componentId' => 'operation'
                                    ]
                                ]
                            ]
                        ]),
                ])
            ])->onEvent([
                'submitSucc' => [
                    'actions' => [
                        [
                            'actionType' => 'custom',
                            'script'     => <<<JS
window.open(event.data.result.data.download_url, '_blank');
JS,

                        ],
                    ]
                ]
            ])
        ]);
    }

    /**
     * 处理流量数据校正
     */
    public function handleFlowDataCorrection()
    {
        try {
            $filePath = request()->input('file')['value'] ?? '';
            $operation = request()->input('operation');
            $filePath = storage_path('app/public/'.$filePath);

            if (empty($filePath) || !file_exists($filePath)) {
                return $this->response()->fail('请上传有效的文件');
            }

            // 检查文件类型
            $extension = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($extension, ['xlsx'])) {
                return $this->response()->fail('只支持.xlsx格式的文件');
            }

            // 读取Excel文件
            $spreadsheet = IOFactory::load($filePath);
            $worksheet = $spreadsheet->getActiveSheet();

            // 处理第7行的第3列和第5列
            $value3 = $worksheet->getCell('C7')->getValue();
            $value5 = $worksheet->getCell('E7')->getValue();
            
            if (is_numeric($value3)) {
                $worksheet->setCellValue('C7', $this->calculateNewValue($value3, $operation));
            }
            if (is_numeric($value5)) {
                $worksheet->setCellValue('E7', $this->calculateNewValue($value5, $operation));
            }

            // 处理第9行开始到最后一行的第2列和第3列
            $row = 9;
            while ($worksheet->getCell('A'.$row)->getValue() !== null) {
                $value2 = $worksheet->getCell('B'.$row)->getValue();
                $value3 = $worksheet->getCell('C'.$row)->getValue();
                
                if (is_numeric($value2)) {
                    $worksheet->setCellValue('B'.$row, $this->calculateNewValue($value2, $operation));
                }
                if (is_numeric($value3)) {
                    $worksheet->setCellValue('C'.$row, $this->calculateNewValue($value3, $operation));
                }
                
                $row++;
            }

            // 保存到public目录
            $filename = uniqid('processed_') . '.' . $extension;
            $processedFile = public_path('excel/' . $filename);
            
            // 确保excel目录存在
            if (!file_exists(public_path('excel'))) {
                mkdir(public_path('excel'), 0755, true);
            }
            
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save($processedFile);

            // 直接返回文件下载地址
            return $this->response()->success([
                'msg' => '处理成功',
                'download_url' => url('excel/' . $filename)
            ]);





        } catch (\Exception $e) {
            return $this->response()->fail('处理失败：' . $e->getMessage());
        }
    }
    /**
     * 根据操作类型计算新值
     */
    private function calculateNewValue($value, $operation)
    {
        $factor = 1.024;
        $factor2=mt_rand(1020, 1030) / 1000;
        
        switch ($operation) {
            case 'multiply_1':
                return $value * $factor;
            case 'multiply_2':
                return $value * $factor * $factor;
            case 'multiply_3':
                return $value * $factor * $factor * $factor;
            case 'divide_1':
                return $value / $factor;
            case 'divide_2':
                return $value / ($factor * $factor);
            case 'divide_3':
                return $value / ($factor * $factor * $factor);
            case 'random_multiply':
                return $value * $factor2;
            case 'random_divide':
                return $value / $factor2;
            default:
                return $value;
        }
    }
    // 流量图生成页面
    public function flowDataCharts()
    {
        return amis()->Page()->body([
            // 上方上传区域
            amis()->Card()->className('mb-3')->body([
                amis()->Alert()
                    ->showIcon(true)
                    ->level('info')
                    ->body('请上传流量数据表格(xlsx格式)，文件格式要求：第1行第2列为图表标题，第3-4行第2列为时间范围，第9行开始为流量数据。'),
                
                amis()->Form()
                    ->title('流量图生成工具')
                    ->api('post:/tools/flow-charts/upload')
                    ->body([
                        amis()->FileControl('file')
                            ->label('上传文件')
                            ->accept('.xlsx')
                            ->drag(true)
                            ->multiple(false)
                            ->required(true)
                            ->joinValues(false)
                            ->autoUpload(true)
                    ])
                    ->onEvent([
                        'submitSucc' => [
                            'actions' => [
                                [
                                    'actionType' => 'reload',
                                    'componentId' => 'flow-chart',
                                    
                                ]
                            ]
                        ]
                    ])
            ]),
            
            // 下方图表区域
            amis()->Card()->className('mt-3')->body([
                Components::make()->makeChart()
                    ->id('flow-chart')
            ])
        ]);
    }

    /**
     * 处理流量图表数据上传
     * @return mixed
     */
    public function handleFlowChartsUpload()
    {
        try {
            // 获取上传的文件
            $filePath = request()->input('file')['value'] ?? '';
            $filePath = storage_path('app/public/'.$filePath);

            if (empty($filePath) || !file_exists($filePath)) {
                return $this->response()->fail('请上传有效的文件');
            }

            // 检查文件类型
            $extension = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($extension, ['xlsx'])) {
                return $this->response()->fail('只支持.xlsx格式的文件');
            }

            // 读取Excel文件
            $spreadsheet = IOFactory::load($filePath);
            $worksheet = $spreadsheet->getActiveSheet();

            // 读取基本信息
            $chartTitle = $worksheet->getCell('B1')->getValue();
            
            // 正确处理Excel时间格式
            $timeStart = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject(
                $worksheet->getCell('B3')->getValue()
            )->format('Y-m-d H:i:s');
            
            $timeEnd = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject(
                $worksheet->getCell('B4')->getValue()
            )->format('Y-m-d H:i:s');

            // 读取流量数据
            $flowData = [];
            $row = 9;
            while ($worksheet->getCell('A'.$row)->getValue() !== null) {
                $timeline = $worksheet->getCell('A'.$row)->getValue();
                // 如果是Excel时间格式，进行转换
                if (is_numeric($timeline)) {
                    $timeline = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($timeline)
                        ->format('Y-m-d H:i:s');
                }
                // in_rates和out_rates保留两位小数
                $in_rates = round($worksheet->getCell('B'.$row)->getValue(), 2);
                $out_rates = round($worksheet->getCell('C'.$row)->getValue(), 2);
                $flowData[] = [
                    'timeline_5min' => $timeline,
                    'in_rates' =>  round($worksheet->getCell('B'.$row)->getValue(), 2),
                    'out_rates' => round($worksheet->getCell('C'.$row)->getValue(), 2),
                ];
                $row++;
            }

            // 准备图表数据
            $chartData = [
                'title' => $chartTitle,
                'time_start' => $timeStart,
                'time_end' => $timeEnd,
                'flowData' => $flowData
            ];

            // 使用Cache存储数据，设置60分钟过期
            Cache::put('flow_chart_data', $chartData, now()->addMinutes(60));

            return $this->response()->success([
                'msg' => '数据上传成功',
                'data' => $chartData
            ]);

        } catch (\Exception $e) {
            return $this->response()->fail('处理失败：' . $e->getMessage());
        }
    }

    /**
     * 获取流量图表数据
     * @return mixed
     */
    public function getFlowChartsData()
    {
        try {
            // 从Cache获取数据
            $chartData = Cache::get('flow_chart_data');
            
            if (empty($chartData)) {
                return $this->response()->fail('请先上传数据文件');
            }

            // 返回图表所需格式的数据
            return $this->response()->success([
                'switch_name' => $chartData['title'] ?? '',
                'port_name' => '',
                'time_start' => $chartData['time_start'] ?? '',
                'time_end' => $chartData['time_end'] ?? '',
                'flowData' => $chartData['flowData'] ?? [],
                'dataType' => $chartData['dataType'] ?? 1000
            ]);

        } catch (\Exception $e) {
            return $this->response()->fail('获取数据失败：' . $e->getMessage());
        }
    }


}